﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Win32;
using System.IO;

namespace Agnes
{
    public class AgnesFileTypeRegister
    {
        private static readonly string _extendName = ".agsln";

        private static readonly string _icon = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "file.ico");

        private static readonly string _description = "Agnes Solution File";

        private static readonly string _exePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Agnes.exe");

        /// <summary>
        ///
        /// </summary>        
        private static bool FileTypeRegistered(string extendName)
        {
            RegistryKey softwareKey = Registry.ClassesRoot.OpenSubKey(extendName);
            if (softwareKey != null)
            {
                return true;
            }

            return false;
        }

        /// <summary>
        ///
        /// </summary>        
        public static void RegisterFileType()
        {
            if (FileTypeRegistered(_extendName))
                return;

            string relationName = _extendName;

            RegistryKey fileTypeKey = Registry.ClassesRoot.CreateSubKey(_extendName);
            fileTypeKey.SetValue("" ,relationName) ;
            fileTypeKey.Close() ;
            
            RegistryKey relationKey = Registry.ClassesRoot.CreateSubKey(relationName) ;
            relationKey.SetValue("", _description);

            RegistryKey iconKey = relationKey.CreateSubKey("DefaultIcon") ;
            iconKey.SetValue("" , _icon) ;

            RegistryKey shellKey   = relationKey.CreateSubKey("Shell") ;
            RegistryKey openKey    = shellKey.CreateSubKey("Open") ;
            RegistryKey commandKey = openKey.CreateSubKey("Command") ;
            commandKey.SetValue("" , _exePath + " %1") ;        
            
            relationKey.Close() ;
        }

        /// <summary>
        /// UpdateFileTypeRegInfo 
        /// </summary>    
        public static bool UpdateFileTypeRegInfo()
        {
           if (!FileTypeRegistered(_extendName))
            {
                return false;
            }

            string relationName = _extendName;
            RegistryKey relationKey = Registry.ClassesRoot.OpenSubKey(relationName, true);
            relationKey.SetValue("", _description);

            RegistryKey iconKey = relationKey.OpenSubKey("DefaultIcon", true);
            iconKey.SetValue("", _icon);

            RegistryKey shellKey = relationKey.OpenSubKey("Shell");
            RegistryKey openKey = shellKey.OpenSubKey("Open");
            RegistryKey commandKey = openKey.OpenSubKey("Command", true);
            commandKey.SetValue("", _exePath + " %1");

            relationKey.Close();
            return true;
        }


    }
}
